package com.org.interceptor;

import com.org.context.BaseContext;
import com.org.exception.BaseException;
import com.org.properties.JwtProperties;
import com.org.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Enumeration;

@Component
@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入拦截器");
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //1.获取请求头
        log.info("请求头中的 token 名称为：{}", jwtProperties.getPcTokenName());
        String token = request.getHeader(jwtProperties.getPcTokenName());
        //2.判断token是否存在
        if(token == null){
            log.info("用户未登录");
            throw new BaseException("未登录,请先登录");
        }
        //3.判断token是否过期
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getPcSecretKey(), token);
            log.info("用户已登录");
            Long userId = Long.valueOf(claims.get("userId").toString());
            log.info("用户Id为：" + userId);
            BaseContext.setCurrentId(userId);
            BaseContext.setThreadLocalToken(token);
        } catch (Exception e) {
            throw new BaseException("登录已过期，请重新登录");
        }
        //4.获取token中的用户Id
        return true;

    }

}
